<template>
	<Div class="collect">
		<Row class="collect-nav">
			<Button icon="arrow-down-a" @click="handleDownloadAll">批量下载</Button>
			<Form :model="searchForm">
				<FormItem>
					<Label>门店名称</Label>
					<Select filterable clearable v-model="searchForm.store_name">
						<Option v-for="item in stores" :value="item.id" :key="item.id">{{ item.store_name }}</Option>
					</Select>
				</FormItem>
				<FormItem>
					<Label>选择时间</Label>
					<DatePicker type="datetime" placeholder="开始时间" format="yyyy-MM-dd HH:mm:ss" @on-change="handleChangeStart"></DatePicker>
					<span>-</span>
					<DatePicker type="datetime" placeholder="结束时间" format="yyyy-MM-dd HH:mm:ss" @on-change="handleChangeEnd"></DatePicker>
				</FormItem>
			</Form>
			<Button icon="ios-search" class="search" @click="handleSearch">查询</Button>
		</Row>
		<Row>
			<Table :columns="code_title" :data="code_data" ref="table" @on-select="handleChangeDown" @on-select-all="handleChangeDownAll" @on-selection-change="handleDownCodeChange"></Table>
      <Page :total="page.total" :current.sync="page.current" show-elevator show-total :page-size="page.size" @on-change="handleChangePage" class-name="page"></Page>
		</Row>

		<Modal v-model="code_down" title="导出二维码" :mask-closable="false" :transfer="false" class-name="code-down" width="720">
			<Form>
				<FormItem>
					<Label>二维码样式：</Label>
					<RadioGroup v-model="code_style" @on-change="codeStyle">
						<Radio v-for="(item,index) in style_radio_group" :label="index" :key="index">{{item.text}}</Radio>
					</RadioGroup>
				</FormItem>
				<!-- <FormItem>
					<Label>是否固定金额：</Label>
					<RadioGroup v-model="is_fixed">
						<Radio v-for="(item,index) in fixed_radio_group " :label="index" :key="index">{{item.text}}</Radio>
						<Input v-if="is_fixed === 1" placeholder="输入金额"></Input>
					</RadioGroup>
				</FormItem> -->
				<FormItem v-if="code_style !== 2">
					<Label>支付方式：</Label>
					<CheckboxGroup v-model="fruit" @on-change="payCheck">
						<Checkbox v-for="(item,index) in pay_check_group" :label="index" :key="index">{{item.text}}</Checkbox>
					</CheckboxGroup>
				</FormItem>
			</Form>
			<Div>
				<p>样本示例：</p>
				<Canvas width="230" height="323" ref="canvas">
					您的浏览器不支持Canvas，请升级最新版本浏览器！
				</Canvas>
			</Div>
			<Div slot="footer"><Button type="primary" @click="handleCodeDownload">确认导出</Button></Div>
		</Modal>
		<a ref="down" style="display:none;"></a>
	</Div>
</template>

<script>
import { codeListInit, storesInit, handleCodeQrcodeSearch, handleCodeQrcodePage, handleDownCode, handleDownCodeAll } from '@/api/order'

export default {
	name: 'collect',
	data(){
		return {
			show: false,
			table_index: '',
			fruit: [],
      check_list:[],
      download:[],
			code_down: false,
			code_style: 0,
			code_style_check:'',
			img_base64: '',
			style_radio_group:[
				{
					text: '样式一',
					url: process.api.MAT_HOST + '/merchant/qrcodes/canvas-bg1.png'
				},
				{
					text: '样式二',
					url: process.api.MAT_HOST + '/merchant/qrcodes/canvas-bg2.png'
				},
				{
					text: '简易版',
					url: null
				}
			],
			fixed_radio_group:[
				{
					text: '非固定'
				},
				{
					text: '固定金额'
				}
			],
			pay_check_group:[
				{
					text: '微信支付',
					url: process.api.MAT_HOST + '/merchant/qrcodes/wx.png'
				},
				{
					text: '支付宝',
					url: process.api.MAT_HOST + '/merchant/qrcodes/zfb.png'
				},
				{
					text: '翼支付',
					url: process.api.MAT_HOST + '/merchant/qrcodes/yzf.png'
				},
				{
					text: '银联支付',
					url: process.api.MAT_HOST + '/merchant/qrcodes/yl.png'
				},
				{
					text: '京东钱包',
					url: process.api.MAT_HOST + '/merchant/qrcodes/jd.png'
				}
			],
			is_fixed: 0,
			code_title:[
				{
					type: 'selection',
					width: 60,
					align: 'center'
				},
				{
					title: '序号',
					key: 'id',
					align: 'center'
				},
				{
					title: '二维码',
					key: 'url',
					align: 'center',
					render:(h,params)=>{
						return h('img',{
							attrs:{
							   src: params.row.url
							},
							style:{
								width: '55px',
								height: '55px',
								margin: '15px 0',
								verticalAlign: 'middle'
							}
						})
					}
				},
				{
					title: '二维码编号',
					key: 'busin_code',
					align: 'center',
					render:(h,params)=>{
						return h('span', {}, params.row.busin_code === '' ? '未绑定' : params.row.busin_code)
					}
				},
				{
					title: '所属门店',
					key: 'store_name',
					align: 'center'
				},
				// {
				// 	title: '是否固定',
				// 	key: 'is_fixed',
				// 	align: 'center'
				// },
				// {
				// 	title: '金额',
				// 	key: 'money',
				// 	align: 'center'
				// },
				{
					title: '添加时间',
					key: 'created_at',
					align: 'center'
				},
				// {
				// 	title: '状态',
				// 	key: 'state',
				// 	align: 'center'
				// },
				{
					title: '操作',
					align: 'center',
					render:(h,params)=>{
						return h('Div',[
							// h('Button',{
							// 	props:{
							// 		type: 'text'
							// 	},
							// 	style:{
							// 		color: '#ff9000'
							// 	},
							// 	on:{
							// 		click:()=>{
							// 			// this.edit_shop = true;
							// 			// this.editShop(params.index);
							// 		}
							// 	}
							// },'修改'),
							// h('Poptip',{
							// 		props: {
							// 		confirm: true,
							// 		title: '您确定要删除这条数据吗?',
							// 		transfer: true
							// 	},
							// 	on: {
							// 		'on-ok': () => {
							// 			// this.store_data.splice(params.index, 1);
							// 		}
							// 	}
							// },[
							// 	h('Button',{
							// 			props: {
							// 				type: 'text'
							// 			},
							// 			style: {
							// 				color: '#c63232'
							// 			}
							// 		},'删除')
							// 	]),
								h('Button',{
									props:{
										type: 'text'
									},
									style:{
										color: '#0078ff'
									},
									on:{
										click:()=>{
											this.code_down = true;
											this.codeDown(params);
										}
									}
								},'二维码导出')
						])
					}
				}
      ],
      searchForm: {
        store_name: '',
        start: '',
        end: ''
      },
      code_data:[],
      page: {
        size: 1,
        total: 0,
        current: 1
      },
      stores: [],
      down: {
        store_id: '',
        style: '',
        softwares: []
      }
		}
	},
	methods:{
		init(){
			codeListInit().then(response => {
        this.code_data = response.data.data.qrcodes
        this.page.current = response.data.data.page
        this.page.total = response.data.data.total
        this.page.size = response.data.data.size
      })
      storesInit().then(response => {
        this.stores = response.data.data.stores
      })
		},
		codeDown(item){
      this.down.store_id = item.row.id
			this.table_index = item.index;   //保存当前项数据下标
			this.check_list = []; //清空多选已选择数组 解决重复保存
			this.fruit = [];    //清空初试多选数组 解决重复保存
			this.code_style_check = 0; //清空单选选已选择数据 解决重复保存
			this.code_style = 0;    //清空初试选择数据 解决重复保存
			this.codeStyle(0);      //默认第一个样式执行
		},
		/*
		*   @ i 背景
		*   @ v 样式选择下标
		*   @ c 二维码
		*   @ l 多选数组
		*   @ t 门店名称
		*/
		canvas(i,v,c,l,t){
			let cav = this.$refs.canvas;  //获取canvas
			let ctx = cav.getContext('2d');   
			let width = cav.width;    //获取canvas宽
			let height = cav.height;  //获取canvas高
			let bg_img = new Image();  //实例化背景 img
			let code_img = new Image(); //实例化二维码 img
			code_img.src = c;
			if(v === 2){         //判断参数
				ctx.clearRect(0,0,width,height);
				ctx.fillStyle = "#eee";
				ctx.fillRect(0,0,width,height);
				ctx.beginPath();
				code_img.onload = ()=>{ //图片加载完成执行
					ctx.drawImage(code_img,50,81.5,130,130);
				}
			}else{
				bg_img.src = i;
				bg_img.onload = ()=>{ //图片加载完成执行
					this.drawImage(ctx,bg_img,code_img,width,height,v);
					if(v === 1){
						ctx.font = "bold 20px Arial";
						ctx.fillStyle = '#fff';
						ctx.textAlign="center";
						ctx.fillText(t,width/2,70);
					}
				}
			}
			if(l.length != 0){
				for(let i=0; i<l.length; i++){
					let logo = new Image();
					logo.src = this.pay_check_group[l[i]].url;
					if(v === 0){
						ctx.beginPath();
						logo.onload = ()=>{
							ctx.drawImage(logo,(i*40)+20,55,32,42);
						}
					}else if(v === 1){
						ctx.beginPath();
						logo.onload = ()=>{
							ctx.drawImage(logo,(i*40)+20,247,32,42);
						}
					}
					
				}
			}
		},
		drawImage(c,bi,ci,w,h,v){ //ctx,img,width,height
			c.clearRect(0,0,w,h);
			c.drawImage(bi,0,0,w,h);
			c.beginPath();
			v === 0 ?  c.drawImage(ci,50,112,130,130) :  c.drawImage(ci,50,88,130,130);
		},
		codeStyle(v){
			this.code_style_check = v;
			if(v === 0){
				let url = this.style_radio_group[v].url; //样式背景
				let code = this.code_data[this.table_index].url;   //当前行二维码
				this.canvas(url,v,code,this.check_list);   //绘制canvas
			}else if(v === 1){
				let url = this.style_radio_group[v].url; //样式背景
				let code = this.code_data[this.table_index].url;   //当前行二维码
				let text = this.code_data[this.table_index].store_name;  //当前行店铺名称
				this.canvas(url,v,code,this.check_list,text);   //绘制canvas
			}else if(v === 2){
				let code = this.code_data[this.table_index].url;   //当前行二维码
				this.canvas(this.style_radio_group[v].url,v,code,[]);
			}
		},
		payCheck(v){
			this.check_list = [];
			this.check_list = v;
			this.codeStyle(this.code_style_check);
		},
		base64ToBlob(code) {
			let parts = code.split(';base64,');
			let contentType = parts[0].split(':')[1];
			let raw = window.atob(parts[1]);
			let rawLength = raw.length;

			let uInt8Array = new Uint8Array(rawLength);

			for (let i = 0; i < rawLength; ++i) {
				uInt8Array[i] = raw.charCodeAt(i);
			}
			return new Blob([uInt8Array], {type: contentType});
		},
		downloadFile(fileName, content) {
			let aLink = document.createElement('a');
			let blob = this.base64ToBlob(content); //new Blob([content]);
			let evt = document.createEvent("HTMLEvents");
			evt.initEvent("click", true, true);//initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
			aLink.download = fileName;
			aLink.href = URL.createObjectURL(blob);

			// aLink.dispatchEvent(evt);
			aLink.click()
		},
    handleChangePage(v) {
      handleCodeQrcodePage(v, this.searchForm).then(response => {
        this.code_data = response.data.data.qrcodes
        this.page.current = response.data.data.page
        this.page.total = response.data.data.total
        this.page.size = response.data.data.size
      })
    },
    handleChangeStart(v) {
      this.searchForm.start = v
    },
    handleChangeEnd(v) {
      this.searchForm.end = v
    },
    handleSearch() {
      handleCodeQrcodeSearch(this.searchForm).then(response => {
        this.code_data = response.data.data.qrcodes
        this.page.current = response.data.data.page
        this.page.total = response.data.data.total
        this.page.size = response.data.data.size
      })
    },
    handleCodeDownload() {
      if (this.down.style === 2) {
        this.down.softwares = []
			} else {
				this.fruit.length === 0 ? this.down.softwares = []: this.down.softwares = this.fruit
				this.down.style = this.code_style
			}
      handleDownCode(this.down).then(response => {
				if (response.data.code === 0) {
					this.downloadFile(new Date().getTime(), response.data.data.qrcode)
				} else {
					this.$Message.error(response.data.message)
				}
      })
    },
    handleChangeDown(v) {
      this.download = v
    },
    handleChangeDownAll(v) {
      this.download = v
    },
    handleDownCodeChange(v) {
      this.download = v
    },
    handleDownloadAll() {
      if (this.download.length !== 0) {
        const data = []
        this.download.forEach(element => {
          data.push(element.id)
				})
        handleDownCodeAll(data).then(response => {
          this.download = []
            let blob = new Blob([response.data], {type: 'application/zip'})
						let objectUrl = URL.createObjectURL(blob)
						window.location.href = objectUrl
						this.$refs.table.selectAll(false)
        })
      } else {
        this.$Message.error('哎呀~没有选择不能下载哟')
      }
    }
	},
	mounted(){
		this.init()
	}
}
</script>

<style lang="less" scoped>
	@import 'code.less';
</style>
